<template>
  <div class="image-cropper">
    <!-- 图片上传 -->
    <el-upload
      action=""
      :before-upload="beforeUpload"
      :show-file-list="false"
      @change="handleFileChange"
    >
      <el-button>上传图片</el-button>
    </el-upload>

    <!-- 显示裁剪界面 -->
    <div v-if="imageSrc" class="cropper-container">
      <img
        ref="image"
        :src="imageSrc"
        alt="image"
        id="image"
        style="width: 100%; max-width: 500px"
      />
      <div class="cropper-buttons">
        <el-button @click="cropImage">裁剪</el-button>
        <el-button @click="saveImage">保存</el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onBeforeUnmount } from 'vue';
import 'cropperjs/dist/cropper.css';
import Cropper from 'cropperjs';
import { ElUpload, ElButton } from 'element-plus';

const imageSrc = ref('');  // 当前图片的 src
const cropperInstance = ref(null);  // Cropper 实例

// 图片上传前的检查
const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/');
  if (!isImage) {
    return false;
  }
  return true;
};

// 图片选择后处理
const handleFileChange = (file) => {
  // 如果有上一个裁剪实例，销毁它
  if (cropperInstance.value) {
    cropperInstance.value.destroy();
    cropperInstance.value = null;
  }

  // 读取文件并显示
  const reader = new FileReader();
  reader.onload = (e) => {
    imageSrc.value = e.target.result;

    // 初始化 Cropper.js
    cropperInstance.value = new Cropper(document.getElementById('image'), {
      aspectRatio: 1,  // 裁剪框的比例
      viewMode: 1,     // 控制裁剪框的行为
      autoCropArea: 0.8,  // 默认裁剪区域占比
    });
  };
  reader.readAsDataURL(file.raw);
};

// 裁剪图片
const cropImage = () => {
  if (cropperInstance.value) {
    const canvas = cropperInstance.value.getCroppedCanvas();
    if (canvas) {
      const croppedImage = canvas.toDataURL('image/png');
      imageSrc.value = croppedImage;  // 更新裁剪后的图片
    }
  } else {
    console.error("Cropper instance is not initialized!");
  }
};

// 保存图片
const saveImage = () => {
  if (cropperInstance.value) {
    const canvas = cropperInstance.value.getCroppedCanvas();
    const link = document.createElement('a');
    link.href = canvas.toDataURL('image/png');
    link.download = 'cropped-image.png';
    link.click();
  } else {
    console.error("Cropper instance is not initialized!");
  }
};

// 组件销毁时销毁 Cropper 实例
onBeforeUnmount(() => {
  if (cropperInstance.value) {
    cropperInstance.value.destroy();
  }
});
</script>

<style scoped>
.image-cropper {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
}

.cropper-container {
  margin-top: 20px;
  position: relative;
  display: inline-block;
}

.cropper-buttons {
  margin-top: 10px;
}

.cropper-buttons el-button {
  margin-right: 10px;
}
</style>
